import axiosMine from "@/utils/axiosMine.js";

const routeCofig = "file-api";
const key = "userInfo";

export const uploadFile = (file, progressCallback) => {
  const formData = new FormData();
  formData.append("file", file);
  formData.append("uploaderId", JSON.parse(localStorage.getItem(key)).id);

  return axiosMine.post(`${routeCofig}/upload`, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
    onUploadProgress: (progressEvent) => {
      if (progressEvent.total) {
        const percent = Math.round(
          (progressEvent.loaded / progressEvent.total) * 100
        );
        progressCallback(percent); // 触发进度回调
      }
    },
  });
};

export const downloadFile = (fileId) => {
  return axiosMine.get(`${routeCofig}/download/${fileId}`, {
    responseType: "blob", // 重要：告诉 axios 以 blob 形式返回数据
  });
};

export const previewFile = (fileId) => {
  return axiosMine.get(`${routeCofig}/preview/${fileId}`, {
    responseType: "blob",
  });
};

export const deleteFile = (fileId) => {
  return axiosMine.post(`${routeCofig}/delete/${fileId}`);
};

export const getUsersuploadedFiles = (userId) => {
  return axiosMine.get(`${routeCofig}/fileList/${userId}`);
};

export const getSubmittedUsers = () => {
  return axiosMine.get(`${routeCofig}/getSubmittedUsers`);
};
